package cn.owen.config;

import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.owen.model.User;
import cn.owen.service.UserService;
import cn.owen.util.MD5Utils;

@Component
public class UserRealm extends AuthorizingRealm {
	@Autowired
	private UserService userService;
	
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		CustomizedToken customizedToken = (CustomizedToken) token;
		
		String name = customizedToken.getUsername();
		char[] credentials  = customizedToken.getPassword();
		
		User user = userService.selectByName(name);
		if (null == user) {
			throw new AccountException("用户名不正确");
		}
		
		if (!MD5Utils.getMD5StringBySign(new String(credentials)).equals(user.getPassword())) {
			throw new AccountException("密码不正确");
		}
		
		if (user.getStatus() == 2) {
			throw new AccountException("帐号已停用");
		}
		ByteSource salt = ByteSource.Util.bytes(name);
		return new SimpleAuthenticationInfo(name,credentials,salt,getName());
	}

	@Override
	public String getName() {
		return "user";
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		return null;
	}
}
